package com.example.controller;

import com.example.dto.dict.DictDetail;
import com.example.dto.dict.DictDetailCriteria;
import com.example.exception.BadRequestException;
import com.example.server.DictDetailServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@Api(tags = "系统：字典详情管理")
@RequestMapping("/api/dictDetail")
public class DictDetailController {
    @Autowired
    private DictDetailServer dictDetailServer;
    private static final String ENTITY_NAME = "dictDetail";

    @ApiOperation("新增字典详情")
    @PostMapping
    public ResponseEntity<Object> createDictDetail(@Validated @RequestBody DictDetail resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        dictDetailServer.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @ApiOperation("删除字典详情")
    @DeleteMapping(value = "/{id}")
    public  ResponseEntity<Object> deleteDictDetail(@PathVariable Long id) {
        dictDetailServer.delete(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改字典详情")
    @PutMapping
    public ResponseEntity<Object> updateDictDetail(@Validated(DictDetail.Update.class)  @RequestBody DictDetail dictDetail){
        dictDetailServer.update(dictDetail);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @ApiOperation("查询字典详情")
    @GetMapping
    public ResponseEntity<Object> findDictDetail(DictDetailCriteria criteria){
        return new ResponseEntity<>(dictDetailServer.findAll(criteria),HttpStatus.OK);
    }

    @ApiOperation("查询多个字典详情")
    @GetMapping(value = "/map")
    public ResponseEntity<Object> getDictDetailMaps(@RequestParam String dictName){
        String[] names = dictName.split("[,，]");
        Map<String, List<DictDetail>> dictMap = new HashMap<>(16);
        for (String name : names) {
            dictMap.put(name, dictDetailServer.getDictByName(name));
        }
        return new ResponseEntity<>(dictMap, HttpStatus.OK);
    }
}
